// ===============================================
// show_alert_dialog
//
// Create by will on 3/4/21 3:16 PM
// Copyright @Will.All rights reserved.
// ===============================================

import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class CoreCustomDialog {
  CoreCustomDialog._internal();
  // static void closeDialog({
  //   required BuildContext context,
  // }) {
  //   Navigator.of(context).popUntil((Route<dynamic> route) {
  //     if (route is DialogRoute) {
  //       CoreKitLogger().d('DialogRoute');
  //       // Navigator.of(context).pop();
  //       Navigator.pop(context);
  //     }
  //     return true;
  //   });
  // }

  static Future<T?> showCustomDialog<T>({
    required BuildContext context,
    required Widget contentWidget,
    //默认显示关闭按钮
    bool isShowCloseBtn = true,
    //默认关闭按钮 在右上角
    AlignmentGeometry? alignment,
    //点击 空白地方 默认不关闭弹窗
    bool barrierDismissible = true,
    BorderRadius? borderRadius,
    GestureTapCallback? onClose,
    //默认的关闭时间 3秒
    Duration? closeDuration,
    //是否自动关闭 默认不自动关闭
    bool isAutoClose = false,
    //遮罩的背景颜色
    Color? barrierColor = Colors.black54,
    //自定义Widget背景颜色
    Color? backgroundColor = Colors.white,
    //是否完全自定义所有内容
    bool? isFullyCustom = false,
    RouteSettings? routeSettings,
    bool useRootNavigator = false,
  }) {
    return showDialog(
      context: context,
      barrierDismissible: barrierDismissible,
      barrierColor: barrierColor,
      routeSettings: routeSettings,
      useRootNavigator: useRootNavigator,
      builder: (ctx) => isFullyCustom!
          ? contentWidget
          : CustomWidget(
              contentWidget: contentWidget,
              alignment: alignment,
              borderRadius: borderRadius,
              isShowCloseBtn: isShowCloseBtn,
              onClose: onClose,
              closeDuration: closeDuration,
              isAutoClose: isAutoClose,
              backgroundColor: backgroundColor,
              isFullyCustom: isFullyCustom,
            ),
    );
  }

  static Future<T?> showCupertinoBottomSheet<T>({
    required BuildContext context,
    required Widget contentWidget,
    //点击 空白地方 默认关闭弹窗
    bool barrierDismissible = true,
    //遮罩的背景颜色
    Color barrierColor = kCupertinoModalBarrierColor,
    bool useRootNavigator = true,
    Color? bgColor,
  }) {
    return showCupertinoModalPopup(
      context: context,
      barrierDismissible: barrierDismissible,
      barrierColor: barrierColor,
      useRootNavigator: useRootNavigator,
      builder: (context) {
        return ScrollConfiguration(
          // A CupertinoScrollbar is built-in below
          behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
          child: Semantics(
            namesRoute: true,
            scopesRoute: true,
            explicitChildNodes: true,
            label: 'Alert',
            child: CupertinoUserInterfaceLevel(
              data: CupertinoUserInterfaceLevelData.elevated,
              child: Container(
                width: MediaQuery.of(context).size.width,
                color: bgColor ?? CupertinoTheme.of(context).barBackgroundColor,
                child: SizedBox(
                  height: MediaQuery.of(context).viewInsets.bottom > 0
                      ? MediaQuery.of(context).size.height / 2
                      : null,
                  child: contentWidget,
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

class CustomWidget extends StatefulWidget {
  const CustomWidget(
      {super.key,
      required this.contentWidget,
      this.alignment,
      this.borderRadius,
      this.isShowCloseBtn,
      this.onClose,
      this.closeDuration,
      this.isAutoClose,
      this.backgroundColor,
      this.isFullyCustom = false});

  final Widget contentWidget;
  final AlignmentGeometry? alignment;
  final BorderRadius? borderRadius;
  final bool? isShowCloseBtn;
  final GestureTapCallback? onClose;
  final Duration? closeDuration;
  final bool? isAutoClose;
  final Color? backgroundColor;
  final bool? isFullyCustom;

  @override
  CustomWidgetState createState() => CustomWidgetState();
}

class CustomWidgetState extends State<CustomWidget> {
  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.isAutoClose != null && widget.isAutoClose!) {
        //Timer的使用需要引入
        final timeout = widget.closeDuration ?? const Duration(seconds: 3);
        Timer(timeout, () {
          Navigator.pop(context);
          widget.onClose!();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: ClipRRect(
        borderRadius: widget.borderRadius ?? BorderRadius.circular(10.0),
        child: Container(
          color: widget.backgroundColor,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Stack(
                alignment: widget.alignment ?? Alignment.topRight,
                children: <Widget>[
                  widget.contentWidget,
                  Offstage(
                    offstage: !widget.isShowCloseBtn!,
                    child: InkWell(
                      child: Container(
                        padding: const EdgeInsets.only(top: 8, right: 8),
                        child: Icon(
                          CupertinoIcons.clear_circled,
                          size: 30,
                          color: CupertinoTheme.of(context).primaryColor,
                        ),
                      ),
                      onTap: () {
                        Navigator.pop(context);
                        widget.onClose!();
                      },
                    ),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
